import { Command } from 'commander'
import { getPackageJson } from './core/utils'
import { parseConfig } from 'confmix'
import buildLibConfigPlugin from './core/build'
import { RollifyConfigure } from './core/typing'
import { printError } from 'node-aux'
import { runRollupBuild } from 'rollup-runner'
const handleAction = async function (type: boolean, options: Record<string, string>) {
    const configPath = options.config

    const { config } = await parseConfig<RollifyConfigure>(configPath)
    const userConfig = buildLibConfigPlugin(config, {
        service: type,
        ...options
    })
    runRollupBuild(
        {
            service: type,
            config: configPath,
            ...options
        },
        userConfig
    )
}
const main = async function () {
    const program = new Command()
    const pkg = await getPackageJson()
    program
        .name('rollify')
        .description('覆盖全场景的构建工具 rollify 脚手架')
        .version(pkg.version)
        // 禁止主命令直接执行（必须带子命令）
        .action(() => {
            program.outputHelp() // 若用户只输入 rollify，直接显示帮助
            process.exit(1)
        })
    program
        .command('service') // 必须带 service 子命令
        .description('开发环境，监听实时打包')
        .option('-c,--config <string>', '配置文件地址', './rollify.config.js')
        .action((options) => handleAction(true, options))
    program
        .command('build') // 必须带 service 子命令
        .description('开发环境，监听实时打包')
        .option('-c,--config <string>', '配置文件地址', './rollify.config.js')
        .action((options) => handleAction(false, options))

    program.parse(process.argv)
}

main().catch((err) => {
    printError('命令执行失败：', err)
    process.exit(1)
})
